package com.sicnu.demo07

import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sicnu.demo07.model.CardMatchingGame

class CardGameActivity : AppCompatActivity() {
    
    private lateinit var recyclerCards: RecyclerView
    private lateinit var tvScore: TextView
    private lateinit var btnRestart: Button
    private lateinit var btnExit: Button
    
    private lateinit var game: CardMatchingGame
    private lateinit var cardAdapter: CardAdapter
    private var itemDecoration: GridSpacingItemDecoration? = null
    private val CARD_COUNT = 36  // 48张牌，确保需要滚动浏览
    private val MATCHING_MODE = 3  // 3张牌游戏模式
    private val handler = Handler(Looper.getMainLooper())
    private var isProcessing = false
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_card_game)
        
        initViews()
        initGame()
        setListeners()
    }
    
    private fun initViews() {
        recyclerCards = findViewById(R.id.recyclerCards)
        tvScore = findViewById(R.id.tvScore)
        btnRestart = findViewById(R.id.btnRestart)
        btnExit = findViewById(R.id.btnExit)
        
        // 根据屏幕方向设置列数
        val spanCount = getSpanCount()
        recyclerCards.layoutManager = GridLayoutManager(this, spanCount)
        
        // 确保RecyclerView可以滚动
        recyclerCards.isNestedScrollingEnabled = true
        recyclerCards.setHasFixedSize(true)
        
        // 添加间距装饰器
        val spacing = 8
        itemDecoration = GridSpacingItemDecoration(spanCount, spacing, true)
        recyclerCards.addItemDecoration(itemDecoration!!)
    }
    
    private fun getSpanCount(): Int {
        // 竖屏4列，横屏6列
        return if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            6
        } else {
            4
        }
    }
    
    private fun initGame() {
        game = CardMatchingGame(CARD_COUNT, MATCHING_MODE)
        isProcessing = false
        
        // 创建卡片列表
        val cards = mutableListOf<com.sicnu.demo07.model.Card>()
        for (i in 0 until CARD_COUNT) {
            cards.add(game.cardAtIndex(i))
        }
        
        // 设置适配器
        cardAdapter = CardAdapter(cards) { position ->
            onCardClick(position)
        }
        recyclerCards.adapter = cardAdapter
        
        updateScore()
    }
    
    private fun onCardClick(index: Int) {
        if (isProcessing) return // 正在处理中，禁止点击
        
        val cardBefore = game.cardAtIndex(index)
        if (cardBefore.isMatched) return // 已匹配的卡片不能点击
        
        // 计算已选中的卡片数量
        val chosenCount = (0 until CARD_COUNT).count { i ->
            val c = game.cardAtIndex(i)
            c.isChosen && !c.isMatched && i != index
        }
        
        game.chooseCardAtIndex(index)
        cardAdapter.notifyDataSetChanged()
        updateScore()
        
        // 如果之前已选中的卡片数量达到了匹配模式-1，需要检查匹配结果
        if (chosenCount == MATCHING_MODE - 1) {
            val cardAfter = game.cardAtIndex(index)
            // 如果这张卡片没有被匹配，说明匹配失败，需要延迟翻回
            if (!cardAfter.isMatched && !cardAfter.isChosen) {
                isProcessing = true
                handler.postDelayed({
                    cardAdapter.notifyDataSetChanged()
                    isProcessing = false
                }, 1000) // 1秒后翻回
            }
        }
    }
    
    private fun updateScore() {
        tvScore.text = game.score.toString()
    }
    
    private fun setListeners() {
        btnRestart.setOnClickListener {
            handler.removeCallbacksAndMessages(null)
            game.reset()
            isProcessing = false
            
            // 重新创建卡片列表
            val cards = mutableListOf<com.sicnu.demo07.model.Card>()
            for (i in 0 until CARD_COUNT) {
                cards.add(game.cardAtIndex(i))
            }
            
            // 更新适配器的卡片列表
            cardAdapter = CardAdapter(cards) { position ->
                onCardClick(position)
            }
            recyclerCards.adapter = cardAdapter
            updateScore()
        }
        
        btnExit.setOnClickListener {
            val resultIntent = Intent().apply {
                putExtra(MainActivity.EXTRA_HIGH_SCORE, game.score)
            }
            setResult(RESULT_OK, resultIntent)
            finish()
        }
    }
    
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
       
        val spanCount = getSpanCount()
        (recyclerCards.layoutManager as? GridLayoutManager)?.spanCount = spanCount
        
        
        itemDecoration?.let { recyclerCards.removeItemDecoration(it) }
        val spacing = 8
        itemDecoration = GridSpacingItemDecoration(spanCount, spacing, true)
        recyclerCards.addItemDecoration(itemDecoration!!)
    }
    
    override fun onBackPressed() {
        handler.removeCallbacksAndMessages(null) // 清除所有延迟任务
        val resultIntent = Intent().apply {
            putExtra(MainActivity.EXTRA_HIGH_SCORE, game.score)
        }
        setResult(RESULT_OK, resultIntent)
        super.onBackPressed()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null) // 清除所有延迟任务
    }
}

